package com.mm.learn.shopping.skill;/**
 * @author wdx
 * @create 2021-08-04 15:07
 */

import org.redisson.Redisson;
import org.redisson.api.RSemaphore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * @author wdx
 * @date 2021年08月04日 15:07
 */
@RestController
public class SkillController {

    private static int NUM = 100;

    @Autowired
    Redisson redisson;

    @GetMapping("/skill/{skuId}")
    public String skills(@PathVariable String skuId) {
//        String s = null;
//        synchronized (this){

/*
        if (NUM <= 0) {
            System.out.println("货品已经抢完");
            return "货品已经抢完";
        }
        NUM = NUM - 1;
             s = UUID.randomUUID().toString();
            System.out.println("抢到货品，订单号为：" + s + "剩余商品数："+ NUM);*/
//        }
        RSemaphore semaphore = redisson.getSemaphore("skill:stock:" + skuId);
        boolean b = semaphore.tryAcquire();
        if (!b) {
            System.out.println("货品已经抢完");
            return "货品已经抢完";
        }
        String s = UUID.randomUUID().toString();
        System.out.println("抢到货品，订单号为：" + s);
        return "抢到货品，订单号为：" + s;
    }

    @GetMapping("/up/{skuId}")
    public String up(@PathVariable String skuId) {
        RSemaphore semaphore = redisson.getSemaphore("skill:stock:" + skuId);
        semaphore.trySetPermits(1000);
        return "成功";
    }
}
